<?php

namespace App\Containers\AppSection\User\Actions;

use App\Containers\AppSection\Authentication\Tasks\RevokeTokensTask;
use App\Containers\AppSection\Log\Tasks\CreateLogTask;
use App\Containers\AppSection\Profile\Tasks\FindLatestProfileByUserIdTask;
use App\Containers\AppSection\User\Tasks\FindUserByIdTask;
use App\Containers\AppSection\User\Tasks\UpdateUserTask;
use App\Containers\AppSection\User\UI\API\Requests\DeleteUserRequest;
use App\Ship\Exceptions\AuthenticationException;
use App\Ship\Parents\Actions\Action;

class DeleteUserAction extends Action
{
    public function run(DeleteUserRequest $request): void
    {
        $user = app(FindUserByIdTask::class)->run($request->id);

        if ($user->trashed()) {
            throw new AuthenticationException('user is deleting');
        }

        app(UpdateUserTask::class)->run(['deleted_at' => now()], $user->id);

        $profile = app(FindLatestProfileByUserIdTask::class)->run($user->id);

        app(RevokeTokensTask::class)->run($user->id);

        app(CreateLogTask::class)->run($profile->id, "Пользователь №{$user->id} удален (админ)", 'user');
        app(CreateLogTask::class)->run($request->profile()->id, "Пользователь №{$user->id} удален", 'user');
    }
}
